package com.yanze.schoolinformation.widget;

import android.content.Context;
import android.os.Handler;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.Interpolator;
import android.widget.RelativeLayout;
import android.widget.Scroller;

import com.yanze.schoolinformation.R;
import com.yanze.schoolinformation.adapter.vp.CommonViewPagerAdapter;
import com.yanze.schoolinformation.adapter.vp.ViewPagerHolderCreator;

import java.lang.reflect.Field;
import java.util.List;

/**
 * 仿魅族广告轮播
 * Created by MrZheng on 2018/3/21.
 */

public class BannerRollplay<T> extends RelativeLayout {
    private ViewPager mViewPager;
    private CommonViewPagerAdapter mAdapter;
    private ViewPagerScroller mViewPagerScroller;//控制ViewPager滑动速度的Scroller
    private int mCurrentItem = 0;//当前位置
    private boolean mIsAutoPlay = true;// 是否自动播放
    public static final long DELAYTIME = 3000;
    private Handler mHandler = new Handler();
    private CommonViewPagerAdapter.BannerPageClickListener mListener;

    public BannerRollplay(Context context) {
        super(context);
        init();
    }

    public BannerRollplay(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public BannerRollplay(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        View view = LayoutInflater.from(getContext()).inflate(R.layout.view_custom_banner, this, true);
        mViewPager = view.findViewById(R.id.viewpager);
        mViewPager.setOffscreenPageLimit(4);
        // 初始化Scroller
        initViewPagerScroll();
    }

    public void setPage(List<T> datas, ViewPagerHolderCreator creator,CommonViewPagerAdapter.BannerPageClickListener listener) {
        mViewPager.setPageTransformer(true, new CoverModeTransformer(mViewPager));
        mAdapter = new CommonViewPagerAdapter(datas, creator, true);
        mAdapter.setUpViewViewPager(mViewPager);
        mAdapter.setPageClickListener(listener);
    }

    //////////////////////////////////开启定时轮播 并判断手指触摸到View时停止轮播
    /**
     * 开始轮播
     * <p>应该确保在调用用了{@link  {@link #(List, )}} 之后调用这个方法开始轮播</p>
     */
    public void start() {
        // 如果Adapter为null, 说明还没有设置数据，这个时候不应该轮播Banner
        if (mAdapter == null) {
            return;
        }
        mIsAutoPlay = true;
        mHandler.removeCallbacks(mLoopRunnable);
        mHandler.postDelayed(mLoopRunnable, DELAYTIME);
    }

    /**
     * 停止轮播
     */
    public void pause() {
        mIsAutoPlay = false;
        mHandler.removeCallbacks(mLoopRunnable);
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        switch (ev.getAction()) {
            // 按住Banner的时候，停止自动轮播
            case MotionEvent.ACTION_MOVE:
            case MotionEvent.ACTION_CANCEL:
            case MotionEvent.ACTION_OUTSIDE:
            case MotionEvent.ACTION_DOWN:
                pause();
                break;
            case MotionEvent.ACTION_UP:
                start();
                break;
        }
        return super.dispatchTouchEvent(ev);
    }

    private final Runnable mLoopRunnable = new Runnable() {
        @Override
        public void run() {
            if (mIsAutoPlay) {
                mCurrentItem = mViewPager.getCurrentItem();
                mCurrentItem++;
                if (mCurrentItem == mAdapter.getCount() - 1) {
                    mCurrentItem = 0;
                    mViewPager.setCurrentItem(mCurrentItem, false);
                    mHandler.postDelayed(this, DELAYTIME);
                } else {
                    mViewPager.setCurrentItem(mCurrentItem);
                    mHandler.postDelayed(this, DELAYTIME);
                }
            } else {
                mHandler.postDelayed(this, DELAYTIME);
            }
        }
    };
    //////////////////////////////////

    /**
     * 仿魅族切换动画
     */
    public class CoverModeTransformer implements ViewPager.PageTransformer {

        private float reduceX = 0.0f;
        private float itemWidth = 0;
        private float offsetPosition = 0f;
        private int mCoverWidth;
        private float mScaleMax = 1.0f;
        private float mScaleMin = 0.9f;
        private ViewPager mViewPager;

        public CoverModeTransformer(ViewPager pager) {
            mViewPager = pager;
        }

        @Override
        public void transformPage(View view, float position) {
            if (offsetPosition == 0f) {
                float paddingLeft = mViewPager.getPaddingLeft();
                float paddingRight = mViewPager.getPaddingRight();
                float width = mViewPager.getMeasuredWidth();
                offsetPosition = paddingLeft / (width - paddingLeft - paddingRight);
            }
            float currentPos = position - offsetPosition;
            if (itemWidth == 0) {
                itemWidth = view.getWidth();
                //由于左右边的缩小而减小的x的大小的一半
                reduceX = (2.0f - mScaleMax - mScaleMin) * itemWidth / 2.0f;
            }
            if (currentPos <= -1.0f) {
                view.setTranslationX(reduceX + mCoverWidth);
                view.setScaleX(mScaleMin);
                view.setScaleY(mScaleMin);
            } else if (currentPos <= 1.0) {
                float scale = (mScaleMax - mScaleMin) * Math.abs(1.0f - Math.abs(currentPos));
                float translationX = currentPos * -reduceX;
                if (currentPos <= -0.5) {//两个view中间的临界，这时两个view在同一层，左侧View需要往X轴正方向移动覆盖的值()
                    view.setTranslationX(translationX + mCoverWidth * Math.abs(Math.abs(currentPos) - 0.5f) / 0.5f);
                } else if (currentPos <= 0.0f) {
                    view.setTranslationX(translationX);
                } else if (currentPos >= 0.5) {//两个view中间的临界，这时两个view在同一层
                    view.setTranslationX(translationX - mCoverWidth * Math.abs(Math.abs(currentPos) - 0.5f) / 0.5f);
                } else {
                    view.setTranslationX(translationX);
                }
                view.setScaleX(scale + mScaleMin);
                view.setScaleY(scale + mScaleMin);
            } else {
                view.setScaleX(mScaleMin);
                view.setScaleY(mScaleMin);
                view.setTranslationX(-reduceX - mCoverWidth);
            }
        }
    }

    /**
     * 设置ViewPager的滑动速度
     */
    private void initViewPagerScroll() {
        try {
            Field mScroller = null;
            mScroller = ViewPager.class.getDeclaredField("mScroller");
            mScroller.setAccessible(true);
            mViewPagerScroller = new ViewPagerScroller(
                    mViewPager.getContext());
            mScroller.set(mViewPager, mViewPagerScroller);

        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }

    /**
     * ＊由于ViewPager 默认的切换速度有点快，因此用一个Scroller 来控制切换的速度
     * <p>而实际上ViewPager 切换本来就是用的Scroller来做的，因此我们可以通过反射来</p>
     * <p>获取取到ViewPager 的 mScroller 属性，然后替换成我们自己的Scroller</p>
     */
    public static class ViewPagerScroller extends Scroller {
        private int mDuration = 1500;// ViewPager默认的最大Duration 为600,我们默认稍微大一点。值越大越慢。
        private boolean mIsUseDefaultDuration = false;

        public ViewPagerScroller(Context context) {
            super(context);
        }

        public ViewPagerScroller(Context context, Interpolator interpolator) {
            super(context, interpolator);
        }

        public ViewPagerScroller(Context context, Interpolator interpolator, boolean flywheel) {
            super(context, interpolator, flywheel);
        }

        @Override
        public void startScroll(int startX, int startY, int dx, int dy) {
            super.startScroll(startX, startY, dx, dy, mDuration);
        }

        @Override
        public void startScroll(int startX, int startY, int dx, int dy, int duration) {
            super.startScroll(startX, startY, dx, dy, mIsUseDefaultDuration ? duration : mDuration);
        }

        public void setUseDefaultDuration(boolean useDefaultDuration) {
            mIsUseDefaultDuration = useDefaultDuration;
        }

        public boolean isUseDefaultDuration() {
            return mIsUseDefaultDuration;
        }

        public void setDuration(int duration) {
            mDuration = duration;
        }

        public int getScrollDuration() {
            return mDuration;
        }
    }
}
